<template>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <!-- 搜索表单区域 -->
        <ElCard class="card-wrapper">
            <ElForm :model="searchParams" label-position="right" :label-width="80">
                <ElRow :gutter="24">
                    <ElCol :lg="6" :md="8" :sm="12">
                        <ElFormItem label="标签名称" prop="tagName">
                            <ElInput v-model="searchParams.tagName" placeholder="请输入（模糊查询）" clearable />
                        </ElFormItem>
                    </ElCol>
                    <ElCol :lg="8" :md="12" :sm="24">
                        <ElFormItem label="创建日期">
                            <ElDatePicker
                                v-model="searchParams.createTime"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                :shortcuts="shortcuts"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                @change="datepickerChange"
                            />
                        </ElFormItem>
                    </ElCol>
                    <ElCol :lg="6" :md="8" :sm="12">
                        <ElFormItem>
                            <ElSpace>
                                <ElButton type="primary" :icon="Search" @click="getTableData">查询</ElButton>
                                <ElButton :icon="RefreshRight" @click="reset">重置</ElButton>
                            </ElSpace>
                        </ElFormItem>
                    </ElCol>
                </ElRow>
            </ElForm>
        </ElCard>

        <!-- 表格卡片区域 -->
        <ElCard class="sm:flex-1-hidden card-wrapper">
            <template #header>
                <div class="flex items-center justify-between">
                    <p>标签管理</p>
                    <ElButton type="primary" @click="handleAdd">
                        <template #icon>
                            <Plus />
                        </template>
                        新增
                    </ElButton>
                </div>
            </template>
            
            <div class="h-[calc(100%-50px)]">
                <ElTable
                    v-loading="tableLoading"
                    height="100%"
                    border
                    class="sm:h-full"
                    :data="tableData"
                    row-key="id"
                >
                    <ElTableColumn type="index" label="序号" width="60" />
                    <ElTableColumn prop="name" label="标签名称" min-width="180">
                        <template #default="scope">
                            <ElTag class="ml-2" type="info">{{ scope.row.name }}</ElTag>
                        </template>
                    </ElTableColumn>
                    <ElTableColumn prop="createTime" label="创建时间" width="180" />
                    <ElTableColumn label="操作" width="120" align="center">
                        <template #default="scope">
                            <ElButton type="danger" size="small" @click="deleteTagSubmit(scope.row)">
                                <template #icon>
                                    <Delete />
                                </template>
                                删除
                            </ElButton>
                        </template>
                    </ElTableColumn>
                </ElTable>
            </div>
            
            <div class="mt-20px flex justify-end">
                <ElPagination
                    v-if="total"
                    layout="total,prev,pager,next,sizes"
                    :current-page="current"
                    :total="total"
                    :page-size="size"
                    :page-sizes="[10, 20, 50]"
                    @current-change="getTableData"
                    @size-change="handleSizeChange"
                />
            </div>
        </ElCard>

        <!-- 新增标签对话框 -->
        <ElDialog v-model="isTagPublishDialogShow" title="新增标签" width="400px">
            <ElForm ref="formRef" :model="form" :rules="rules" label-position="top">
                <ElFormItem label="标签名称" prop="tags">
                    <ElTag v-for="tag in dynamicTags" :key="tag" class="mx-1 mb-2" closable :disable-transitions="false"
                        @close="handleClose(tag)" type="info" round>
                        {{ tag }}
                    </ElTag>
                    <ElInput v-if="inputVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20 mb-2" size="small"
                        @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                    <ElButton v-else class="button-new-tag ml-1 mb-2" size="small" @click="showInput" round>
                        + 新增标签
                    </ElButton>
                </ElFormItem>
            </ElForm>
            <template #footer>
                <ElSpace>
                    <ElButton @click="isTagPublishDialogShow = false">取消</ElButton>
                    <ElButton type="primary" @click="addTagsSubmit">提交</ElButton>
                </ElSpace>
            </template>
        </ElDialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import { ref, reactive, nextTick } from 'vue'
import { addTags, getTagPageList, deleteTag } from '@/service/api/blog/label'
import { showMessage } from '@/composables/util'
import { Search, RefreshRight, Plus, Delete } from '@element-plus/icons-vue'

defineOptions({ name: 'TagManage' })

const isTagPublishDialogShow = ref(false)

// 搜索参数
const searchParams = reactive({
    tagName: '',
    createTime: '',
    startDate: '',
    endDate: ''
})

const reset = () => {
    searchParams.tagName = ''
    searchParams.createTime = ''
    searchParams.startDate = ''
    searchParams.endDate = ''
    getTableData()
}

const datepickerChange = (dates: any) => {
    if (dates && dates.length === 2) {
        searchParams.startDate = dates[0]
        searchParams.endDate = dates[1]
    } else {
        searchParams.startDate = ''
        searchParams.endDate = ''
    }
}

const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]

const form = reactive({
    tags: [] as string[]
})

const formRef = ref<any>(null)
const rules = {
    tags: [
        { required: true, message: '请至少添加一个标签', trigger: 'change' },
    ]
}

const inputValue = ref('')
const dynamicTags = ref<string[]>([])
const inputVisible = ref(false)
const InputRef = ref<any>(null)

const handleClose = (tag: string) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value?.focus()
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        dynamicTags.value.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

const handleAdd = () => {
    dynamicTags.value = []
    isTagPublishDialogShow.value = true
}

const addTagsSubmit = async () => {
    try {
        form.tags = dynamicTags.value
        if (form.tags.length === 0) {
            showMessage('请至少添加一个标签', 'warning')
            return
        }

        const res = await addTags(form)
        
        showMessage('添加成功', 'success')
        isTagPublishDialogShow.value = false
        dynamicTags.value = []
        getTableData()
    } catch (error) {
        console.error('添加标签失败:', error)
        showMessage('添加失败', 'error')
    }
}

const tableLoading = ref(false)
const tableData = ref<any[]>([])
const current = ref(1)
const total = ref(0)
const size = ref(10)

// 获取分页数据
async function getTableData() {
    try {
        tableLoading.value = true
        const params = {
            current: current.value,
            size: size.value,
            tagName: searchParams.tagName,
            startDate: searchParams.startDate,
            endDate: searchParams.endDate
        }
        
        const res = await getTagPageList(params)
        if (res.data != null) {
            tableData.value = res.data.records || res.records || []
            current.value = res.data.current || current.value
            total.value = res.data.total || 0
            size.value = res.data.size || size.value
        } else {
            showMessage(res.message || '获取数据失败', 'error')
            tableData.value = []
        }
    } catch (error) {
        console.error('获取数据失败:', error)
        showMessage('获取数据失败', 'error')
        tableData.value = []
    } finally {
        tableLoading.value = false
    }
}

// 初始化数据
getTableData()

const handleSizeChange = (newSize: number) => {
    size.value = newSize
    current.value = 1
    getTableData()
}

const deleteTagSubmit = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            '是否确认要删除该标签?',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        
        const res = await deleteTag(row.id)
        
        showMessage('删除成功', 'success')
        getTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            showMessage('删除失败', 'error')
        }
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-card) {
  .card-wrapper {
    height: 100%;
  }
}
</style>